package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.spzx.manager.listener.CategoryExcelDtoListener;
import com.atguigu.spzx.manager.listener.CategoryExcelDtoListener2;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import com.atguigu.spzx.model.dto.product.CategoryExcelDto;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.exception.SpzxException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    @Resource
    CategoryExcelDtoListener categoryExcelDtoListener;

    @Override
    public List<Category> findByPid(Long pid) {
        List<Category> categories = categoryMapper.findByPid(pid);

        categories.forEach(category -> {
            //使用正在遍历的分类的id 查询它是否有下一级分类
            category.setHasChildren(categoryMapper.hasChildren(category.getId()));
        });

        return categories;
    }
    //解析前端传入的excel文件中的分类数据
    //都保存到分类表中
    @CacheEvict(value = "product:cates" , key = "'all'")
    @Override
    public void importCates(MultipartFile excel) {
        //1、为excel创建javabean DTO
        //2、创建回调监听器：编写读取到数据保存到数据库的业务
        //3、使用EasyExcel读取数据

        try {
            EasyExcel.read(excel.getInputStream())
                    .head(CategoryExcelDto.class)
//                    .registerReadListener(categoryExcelDtoListener)
                    .registerReadListener(new CategoryExcelDtoListener2(categoryMapper))
//                    .she
                    .doReadAll();//不指定sheet时 会读取所有的工作簿内容
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }

    @Override
    public void exportCates(HttpServletResponse response) {

        try {
            //查询所有的分类数据
            List<CategoryExcelDto> categoryExcelDtos = categoryMapper.findAll();
            //手写响应报文：
            //1、响应报文头：设置响应体内容的格式(类型、是否为一个附件：触发浏览器下载、文件名称)

            //包含中文的请求头配置时会导致数据丢失 可以使用UrlEncode对中文编码，前端会自动使用UrlDecode解码
            String fileName = URLEncoder.encode("商品分类列表_"+System.currentTimeMillis()+ ExcelTypeEnum.XLSX.getValue());
//            response.setContentType 导出文件时可以不指定content-type
            response.setHeader("content-disposition" , "attachment:file;" +
                    "filename="+fileName);
            //2、响应报文体：将分类数据写到excel文件中  将文件流设置到响应体中
            //写入到excel文件中
            EasyExcel.write(response.getOutputStream()) //将excel文件写到一个输出流中
                    .sheet("分类列表") //工作簿名称
                    .head(CategoryExcelDto.class) //对应表头的类
                    .doWrite(categoryExcelDtos);//数据集合

        } catch (Exception e) {
            throw new SpzxException( ResultCodeEnum.FILE_EXPORT_ERROR, e);
        }


    }
}
